<template>
  <div class="tree-box">
    <el-input
      v-if="!noSearch"
      v-model="filterText"
      :placeholder="placeholder"
      prefix-icon="el-icon-search"
    />
    <div class="title">{{ title }}</div>
    <div class="content" :class="{noSearch}">
      <el-tree
        ref="tree"
        node-key="id"
        :filter-node-method="filterNode"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        v-bind="$attrs"
        :props="defaultProps"
        :data="data"
        @node-click="handleNodeClick"
      />
      <slot />
    </div>
  </div>
</template>

<script>
export default {
  name: 'TreeBox',
  model: {
    prop: 'selectedNode',
    event: 'change'
  },
  props: {
    noSearch: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入机构名称搜索'
    },
    selectedNode: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Array,
      default() {
        return []
      }
    },
    defaultProps: {
      type: Object,
      default() {
        return {
          children: 'nodes',
          label: 'name'
        }
      }
    }
  },
  data() {
    return {
      curNode: {},
      filterText: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    data: {
      handler(val) {
        if (this.data.length > 0) {
          this.$nextTick(() => {
            this.$refs.tree.setCurrentNode(this.data[0])
          })
          this.handleNodeClick(this.data[0])
        }
      },
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleNodeClick(item) {
      if (item.id !== this.curNode.id) {
        this.curNode = item
        this.$emit('change', item)
      }
    },
    getCheckedNodes() {
      return this.$refs.tree.getCheckedNodes()
    },
    getHalfCheckedNodes() {
      return this.$refs.tree.getHalfCheckedNodes()
    },
    setCheckedNodes(data) {
      return this.$refs.tree.setCheckedNodes(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-box {
  height: 100%;
  .title{
    text-align: center;
    line-height:34px;
    background: #426ab6;
    color: #fff;
    margin-top: 10px;
  }
  .content{
    height: calc(100% - 44px - 40px);
    padding: 10px 0;
    overflow: auto;
    &.noSearch{
      height: calc(100% - 44px);
    }
  }
}
</style>
